package com.byxy.computer.student.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.byxy.computer.student.entity.LessonMaterial;
import com.byxy.computer.student.entity.Student;
import com.byxy.computer.student.service.LessonMaterialService;
import com.byxy.computer.student.service.StudentService;
import com.byxy.computer.student.utils.ZipUtil;
import com.byxy.computer.utils.excel.ExportExcel;
import com.byxy.computer.utils.excel.ImportExcel;

/**
 * @author Daniel
 * @E-Mail iva0512@gmail.com
 * @Date 2016年9月25日
 */
@Controller
@RequestMapping("tch")
@SessionAttributes("students")
public class TeacherController {

	@Autowired
	private StudentService studentService;
	@Autowired
	private LessonMaterialService lessonMaterialService;

	// 老师主页
	@RequestMapping(value = { "" }, method = RequestMethod.GET)
	public String index() {
		return "redirect:tch/";
	}

	// 老师主页
	@RequestMapping(value = { "index", "/" }, method = RequestMethod.GET)
	public String index2() {
		return "teacher/login";
	}

	// 登录
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(String uid, String pwd) {
		if("admin".equals(uid) && "admin".equals(pwd))
			return "redirect:list";
		else
			return "teacher/login";
	}

	// 退出
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(Model model) {
		model.asMap().remove("students");
		return "redirect:tch/index";
	}

	// 学生的所有数据
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(Model model) {
		List<Student> stds = studentService.listAll();
		model.addAttribute("students", stds);
		model.addAttribute("total", stds.size());
		int count = 0;
		for (Student s : stds) {
			if (s.getStats() != null && !"K".equals(s.getStats()) && !"S".equals(s.getStats())
					&& !"B".equals(s.getStats())) {
				count++;
			}
		}
		model.addAttribute("arrival", count);
		return "teacher/list";
	}

	// 用json返回学生的所有数据
	@RequestMapping(value = "list_json", method = RequestMethod.GET)
	@ResponseBody
	public List<Student> list_json(Model model) {
		List<Student> stds = studentService.listAll();
		model.addAttribute("students", stds);
		model.addAttribute("total", stds.size());
		int count = 0;
		for (Student s : stds) {
			if (s.getStats() != null && !"K".equals(s.getStats()) && !"S".equals(s.getStats())
					&& !"B".equals(s.getStats())) {
				count++;
			}
		}
		model.addAttribute("arrival", count);
		return stds;
	}

	// 导入学生数据
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public String upload(MultipartFile attach)
			throws InvalidFormatException, IOException, InstantiationException, IllegalAccessException {
		ImportExcel imp = new ImportExcel(attach, 0, 0);
		List<Student> stds = imp.getDataList(Student.class, null);
		studentService.save(stds);
		return "redirect:list";
	}

	// 导入学生数据页面
	@RequestMapping(value = "importxls", method = RequestMethod.GET)
	public String importdata() {
		return "teacher/import";
	}

	// 导出学生数据
	@RequestMapping(value = "exportxls", method = RequestMethod.GET)
	public void exportxls(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String excelTitle = DateFormat.getDateInstance().format(new Date()) + "_Attendance";// Student.class.getSimpleName();
		List<Student> records = studentService.listAll();
		String fileName = excelTitle + ".xls";
		new ExportExcel(null, Student.class).setDataList(records).write(response, fileName).dispose();
	}

	@RequestMapping(value = "deleteAll", method = RequestMethod.GET)
	public String deleteAll() {
		studentService.deleteAll();
		return "redirect:list";
	}

	// 导出数据模板
	@RequestMapping(value = "exportemp", method = RequestMethod.GET)
	public void exportemp(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String excelTitle = Student.class.getSimpleName();
		List<Student> records = new ArrayList<Student>();
		Student s = new Student("1821604444", "王小明");
		records.add(s);
		String fileName = excelTitle + ".xls";
		new ExportExcel(null, Student.class).setDataList(records).write(response, fileName).dispose();
	}

	// 下载学生的作业
	@RequestMapping("download")
	public void download(String fileName, HttpServletRequest request, HttpServletResponse response) {
		String realpath = request.getSession().getServletContext().getRealPath("/");
		int len = fileName.lastIndexOf("/");
		if (len > 0) {
			String name = fileName.substring(len + 1);
			// System.out.println(realpath + "/upload/" + fileName);
			File file = new File(realpath + "/upload/" + fileName);
			if (file.exists()) {
				try {
					String realname = new String(name.getBytes("gbk"), "ISO-8859-1");
					response.reset();
					response.setCharacterEncoding("utf-8");
					response.setContentType("multipart/form-data");
					// response.setContentType("application/x-msdownload");
					response.setHeader("Content-Disposition", "attachment;fileName=" + realname);
					InputStream inputStream = new FileInputStream(file);
					int fileLength = (int) file.length();
					response.setContentLength(fileLength);
					OutputStream os = response.getOutputStream();
					byte[] b = new byte[2048];
					int length;
					while ((length = inputStream.read(b)) > 0) {
						os.write(b, 0, length);
					}
					inputStream.close();
					os.close();
					// inputStream.close();
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// 下载学生的作业
	@RequestMapping("downloadzip")
	public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
		String strDate = DateFormat.getDateInstance().format(new Date());
		String path = "/upload/" + strDate;
		String realpath = request.getSession().getServletContext().getRealPath(path);
		try {
			File file = new File(realpath);
			String realname = new String(strDate.getBytes("gbk"), "ISO-8859-1");
			response.reset();
			response.setCharacterEncoding("utf-8");
			// response.setContentType("application/x-msdownload");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName=" + realname + ".zip");
			OutputStream os = response.getOutputStream();
			ZipOutputStream zipOut = new ZipOutputStream(os);
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; ++i) {
					InputStream input = new FileInputStream(files[i]);
					zipOut.putNextEntry(new ZipEntry(file.getName() + File.separator + files[i].getName()));
					int temp = 0;
					while ((temp = input.read()) != -1) {
						zipOut.write(temp);
					}
					input.close();
				}
			}
			zipOut.close();
			os.close();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 下载学生的作业
	@RequestMapping("downloadzip2")
	public void downloadFile2(HttpServletRequest request, HttpServletResponse response) {
		String strDate = DateFormat.getDateInstance().format(new Date());
		String path = "/upload/" + strDate;
		String realpath = request.getSession().getServletContext().getRealPath(path);
		try {
			String realname = URLEncoder.encode(strDate, "utf-8");
			response.reset();
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName=" + realname + ".zip");
			OutputStream os = response.getOutputStream();
			ZipOutputStream zipOut = new ZipOutputStream(os,Charset.forName("GBK"));
			ZipUtil.zipFiles(realpath, zipOut);
			zipOut.close();
			os.close();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 点赞
	@RequestMapping(value = "good", method = RequestMethod.GET)
	public String good(String uid) {
		studentService.sayGood(new Student(uid, ""));
		return "redirect:list";
	}

	// 点批评
	@RequestMapping(value = "bad", method = RequestMethod.GET)
	public String bad(String uid) {
		studentService.sayBad(new Student(uid, ""));
		return "redirect:list";
	}

	// 清除点名数据
	@RequestMapping(value = "delete", method = RequestMethod.GET)
	public String delete(String uid) {
		studentService.resetLesson(new Student(uid, ""));
		return "redirect:list";
	}

	// 旷课
	@RequestMapping(value = "truant", method = RequestMethod.GET)
	public String truant(String uid) {
		studentService.playTruant(new Student(uid, ""));
		return "redirect:list";
	}

	// 迟到
	@RequestMapping(value = "late", method = RequestMethod.GET)
	public String late(String uid) {
		studentService.beLate(new Student(uid, ""));
		return "redirect:list";
	}

	// 请假
	@RequestMapping(value = "holiday", method = RequestMethod.GET)
	public String holiday(String uid) {
		studentService.holiday(new Student(uid, ""));
		return "redirect:list";
	}

	// 请假
	@RequestMapping(value = "sick", method = RequestMethod.GET)
	public String sick(String uid) {
		studentService.sick(new Student(uid, ""));
		return "redirect:list";
	}

	@RequestMapping(value = "uploadMaterial", method = RequestMethod.GET)
	public String upload() {
		return "teacher/upload";
	}

	// 上传上课资料
	@RequestMapping(value = "uploadMaterial", method = RequestMethod.POST)
	public String upload(@RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) {
		String strDate = "Material";// DateFormat.getDateInstance(DateFormat.SHORT).format(new
									// Date());
		String path = "/upload/" + strDate;
		String realpath = req.getSession().getServletContext().getRealPath(path);

		for (MultipartFile attach : attachs) {
			if (attach.isEmpty())
				continue;
			File f = new File(realpath + "/" + attach.getOriginalFilename());
			try {
				lessonMaterialService.save(
						new LessonMaterial(attach.getOriginalFilename(), strDate + "/" + attach.getOriginalFilename()));
				FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "redirect:list";
	}
}
